<template>
    <view class="view-contain">
        <!-- 公共组件-每个页面必须引入 -->
        <public-module leftIcon="arrow-left" :title="title" />
        <mescroll-uni :height="`${height}px`" :down="downOption" :up="upOption" @init="mescrollInit"
                      @down="downCallback" @up="upCallback">
            <!-- 只显示一个试卷信息 -->
            <view class="province-item" v-if="papersList.length > 0" :key="papersList[0].id">
                <view class="paper-info">
                    <view class="paper-title">{{ papersList[0].name }}</view>
                    <view class="paper-category">{{ papersList[0].category }}</view>
                </view>
                <!-- 问题区域 -->
                <view class="questions-container">
                    <view class="question-label" v-for="(question, questionIndex) in papersList[0].questions"
                          :key="question.id" @click="showQuestionDetail(questionIndex)">
                        问题 {{ questionIndex + 1 }}
                    </view>
                </view>
                <view v-if="selectedQuestionIndex !== null">
                    <view class="question-detail">
                        <view class="question-title">问题内容:</view>
                        <view class="question-description">
                            {{ papersList[0].questions[selectedQuestionIndex].description }}</view>
                        <view class="answer-title">参考答案:</view>
                        <view class="answers-container">
                            <view class="answer-label"
                                  v-for="(answer, answerIndex) in papersList[0].questions[selectedQuestionIndex].answers"
                                  :key="answer.id">
                                <view class="answer-source-and-stats">
                                    <!-- 新增文字答案来源，使用 u-parse 组件显示富文本 -->
                                    <view class="answer-source" @click="toggleAnswerContent(answerIndex)">
                                        答案来源：
                                        <u-parse :content="answer.source"></u-parse>
                                    </view>
                                    <view class="answer-stats">
                                        <view class="like-count" @click="toggleLike(answerIndex)">
                                            <u-icon :name="likeStatus[answerIndex] ? 'thumb-up-fill' : 'thumb-up'" :size="48" />
                                            <text> {{ answer.likeCount !== null ? answer.likeCount : 0 }} </text>
                                        </view>
                                    </view>
                                </view>
                                <!-- 答案内容另起一行，默认隐藏 -->
                                <view class="answer-content" v-if="visibleAnswerIndexes.includes(answerIndex)">
                                    <!-- 使用 u-parse 组件显示答案内容的富文本 -->
                                    <u-parse :content="answer.content"></u-parse>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </mescroll-uni>
    </view>
</template>

<script>
import {
    mapState,
    mapMutations
} from 'vuex';
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import {
    paperDetail,
    answerLike
} from "@/config/api.js";
import uParse from '@/uni_modules/uview-ui/components/u-parse/u-parse.vue'; // 引入 u-parse 组件

export default {
    mixins: [MescrollMixin], // 使用mixin
    components: {
        uParse // 注册 u-parse 组件
    },
    data() {
        return {
            title: '参考答案',
            height: 0,
            category: '',
            papersList: [],
            downOption: {
                use: false
            },
            upOption: {
                use: false // 禁用上拉加载
            },
            selectedQuestionIndex: null,
            visibleAnswerIndexes: [], // 用于记录每个问题下可见答案的索引
            likeStatus: [] // 用于记录每个答案的点赞状态
        }
    },
    computed: {
        ...mapState(['user'])
    },
    onLoad(option) {
        const {
            id
        } = option;
        this.id = id;
        console.log("当前试卷ID " + this.id);

        // 默认打开问题1
        this.selectedQuestionIndex = 0; // 设置为第一个问题的索引

        // 加载数据
        this.loadData();
    },
    onShow() {
        const res = uni.getSystemInfoSync()
        this.height = res.windowHeight - 150 // 100为组件高度
    },
    methods: {
        ...mapMutations(['setLoginShow', 'emptyUserInfo']),
        async loadData() {
            try {
                const res = await paperDetail(`${this.id}`);
                if (res) {
                    this.papersList = [res.data]; // 确保只显示一个试卷信息
                    // 根据后端返回的 isLiked 初始化 likeStatus 数组
                    if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
                        const answers = this.papersList[0].questions[this.selectedQuestionIndex].answers;
                        this.likeStatus = answers.map(answer => answer.isLiked === 1);
                    }
                } else {
                    this.emptyUserInfo();
                    uni.showModal({
                        title: '提示',
                        content: '当前登录已无效，请重新登陆。',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }
                        }
                    });
                }
            } catch (error) {
                console.error('数据加载失败:', error);
            }
        },
        showQuestionDetail(index) {
            this.selectedQuestionIndex = index; // 设置选中的问题索引
            this.visibleAnswerIndexes = []; // 切换问题时清空可见答案索引
            // 切换问题时更新 likeStatus 数组
            if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
                const answers = this.papersList[0].questions[this.selectedQuestionIndex].answers;
                this.likeStatus = answers.map(answer => answer.isLiked === 1);
            }
        },
        toggleAnswerContent(answerIndex) {
            const index = this.visibleAnswerIndexes.indexOf(answerIndex);
            if (index > -1) {
                this.visibleAnswerIndexes.splice(index, 1); // 隐藏答案
            } else {
                this.visibleAnswerIndexes.push(answerIndex); // 显示答案
            }
        },
        mescrollInit(mescroll) {
            this.mescroll = mescroll;
        },
        downCallback() {
            // 下拉刷新回调，这里禁用了下拉刷新，可留空
        },
        upCallback() {
            // 上拉加载回调，这里禁用了上拉加载，可留空
        },
        async toggleLike(answerIndex) {
            const currentAnswer = this.papersList[0].questions[this.selectedQuestionIndex].answers[answerIndex];
            const answerId = currentAnswer.id; // 获取当前答案的 ID

            // 取消同一问题下其他答案的喜欢状态
            this.papersList[0].questions[this.selectedQuestionIndex].answers.forEach((answer, index) => {
                if (index !== answerIndex) {
                    this.likeStatus[index] = false; // 取消其他答案的喜欢状态
                    answer.isLiked = 0; // 更新 isLiked 字段
                    this.papersList[0].questions[this.selectedQuestionIndex].answers[index].likeCount =
                        this.papersList[0].questions[this.selectedQuestionIndex].answers[index].likeCount > 0
                            ? this.papersList[0].questions[this.selectedQuestionIndex].answers[index].likeCount - 1
                            : 0; // 减少其他答案的点赞数量
                }
            });

            // 切换当前答案的点赞状态
            const isLiked = this.likeStatus[answerIndex];
            this.likeStatus[answerIndex] = !isLiked;
            currentAnswer.isLiked = this.likeStatus[answerIndex] ? 1 : 0; // 更新 isLiked 字段

            // 更新当前答案的点赞数量
            if (this.likeStatus[answerIndex]) {
                this.papersList[0].questions[this.selectedQuestionIndex].answers[answerIndex].likeCount++;
                // 调用后端接口进行点赞
                await answerLike(answerId); // 发送请求
            } else {
                this.papersList[0].questions[this.selectedQuestionIndex].answers[answerIndex].likeCount--;
                // 这里可以选择是否调用后端接口进行取消点赞
                // await answerUnlike(answerId); // 如果有取消点赞的接口
            }
        }
    },
    mounted() {
        // 初始化点赞状态
        if (this.papersList[0].questions && this.papersList[0].questions.length > 0) {
            const answers = this.papersList[0].questions[this.selectedQuestionIndex].answers;
            this.likeStatus = answers.map(answer => answer.isLiked === 1);
        }
    }
};
</script>

<style lang="scss" scoped>
.view-contain {
    flex-direction: column;
    align-items: center;
    background-color: #F5F6F5;
    height: 100vh;
    padding: 20px 8px;
    /* 增加顶部内边距以适配刘海屏 */
}

.welcome-message {
    margin-bottom: 20px;
    font-size: 18px;
    color: #333;
}

.province-list {
    width: 100%;
}

.province-item {
    justify-content: space-between;
    align-items: center;
    width: 100%;
    margin-bottom: 5px;
    border-radius: 5px;
}

.arrow {
    font-size: 18px;
    color: #333;
}

.paper-info {
    margin-bottom: 20px;
    /* 添加底部间距 */
}

.paper-title {
    font-size: 18px;
    /* 调整试卷名称字体大小 */
    text-align: center; // 文字居中对齐
}

.paper-category {
    font-size: 14px;
    /* 调整试卷类别字体大小 */
    color: #666;
    /* 设置颜色 */
    text-align: right;
    margin-right: 15%;
}

.questions-container {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    padding: 8px;
}

.question-label {
    flex: 0 0 14%;
    margin-bottom: 10px;
    padding: 5px 10px;
    background-color: #E0F7FA;
    border-radius: 5px;
    cursor: pointer;
    text-align: center;
}

.question-detail {
    margin-top: 20px;
}

.question-title {
    font-weight: bold;
    margin-bottom: 5px;
}

.question-description {
    margin-bottom: 10px;
    text-indent: 2em;
    width: 98%;
}

.answer-title {
    margin-top: 10px;
    font-weight: bold;
}

.answers-container {
    display: flex;
    flex-direction: column;
    /* 列表模式 */
    margin-top: 10px;
}

.answer-label {
    margin-bottom: 10px;
    /* 每个答案标签之间的间距 */
    padding: 10px;
    background-color: #E0F7FA;
    border-radius: 5px;
    cursor: pointer;
}

.answer-source-and-stats {
    display: flex;
    justify-content: space-between;
    align-items: center;
    /* 修改为水平排列 */
    flex-direction: row;
}

.answer-source {
    cursor: pointer;
}

.answer-stats {
    display: flex;
    justify-content: space-between;
    min-width: 120px;
}

.like-count {
    display: flex;
    align-items: center;
    cursor: pointer;
}

.active {
    color: #007AFF; // 设置激活状态的颜色
}

.answer-content {
    margin-top: 10px;
    font-weight: normal;
    text-indent: 0;
    width: 98%;
}

.selected-answer-content {
    margin-top: 20px;
    padding: 10px;
    background-color: #E0F7FA;
    border-radius: 5px;
}
</style>